package com.quick.controller.system;

import com.quick.common.annotation.Log;
import com.quick.common.core.controller.BaseController;
import com.quick.common.core.domain.ApiResponse;
import com.quick.common.core.domain.LoginUser;
import com.quick.common.enums.BusinessTypeEnum;
import com.quick.common.exception.ServiceException;
import com.quick.common.utils.SecurityUtils;
import com.quick.common.utils.file.FileUploadUtils;
import com.quick.common.utils.file.MimeTypeUtils;
import com.quick.framework.service.TokenService;
import com.quick.system.domain.SysDept;
import com.quick.system.domain.SysPost;
import com.quick.system.domain.SysUser;
import com.quick.system.domain.dto.SysUserDTO;
import com.quick.system.service.SysDeptService;
import com.quick.system.service.SysPostService;
import com.quick.system.service.SysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 个人信息 业务处理
 *
 * @Author: 吃素不吃肉
 * @Date: Tue Jul 25 14:14:44 CST 2023
 */
@RestController
@RequestMapping("/system/user/profile")
public class SysProfileController extends BaseController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysDeptService sysDeptService;
    @Autowired
    private SysPostService sysPostService;

    @Autowired
    private TokenService tokenService;

    /**
     * 个人信息
     */
    @GetMapping
    public ApiResponse profile() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = sysUserService.selectSysUserByUserId(loginUser.getUserId());
        if (Objects.isNull(sysUser)) {
            throw new ServiceException("个人信息不存在");
        }
        SysDept sysDept = sysDeptService.selectSysDeptByDeptId(sysUser.getDeptId());
        Map<String, Object> data = new HashMap<>(1);
        Set<String> roles = loginUser.getRoles().stream().map(LoginUser.Role::getRoleKey).collect(Collectors.toSet());
        List<SysPost> sysPosts = sysPostService.selectSysPostByUserId(loginUser.getUserId());
        data.put("postGroup", String.join(",", sysPosts.stream().map(SysPost::getPostName).collect(Collectors.joining(","))));
        data.put("roleGroup", String.join(",", roles));
        data.put("user", sysUser);
        data.put("dept", sysDept);
        return success(data);
    }

    /**
     * 修改用户
     */
    @Log(title = "个人信息", businessType = BusinessTypeEnum.UPDATE)
    @PutMapping
    public ApiResponse updateProfile(@RequestBody SysUserDTO sysUserDTO) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(sysUserDTO, sysUser);
        sysUser.setUserId(loginUser.getUserId());
        sysUser.setUpdateBy(loginUser.getUsername());
        return ApiResponse.success(sysUserService.updateSysUser(sysUser));
    }

    /**
     * 重置密码
     */
    @Log(title = "个人信息", businessType = BusinessTypeEnum.UPDATE)
    @PutMapping("/updatePwd")
    public ApiResponse updatePwd(String oldPassword, String newPassword) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = sysUserService.selectSysUserByUserId(loginUser.getUserId());
        String userName = user.getUserName();
        String password = user.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password)) {
            throw new ServiceException("旧密码错误！");
        }
        if (SecurityUtils.matchesPassword(newPassword, password)) {
            throw new ServiceException("新密码不能与旧密码相同！");
        }
        String encryptPassword = SecurityUtils.encryptPassword(newPassword);
        SysUser sysUser = new SysUser();
        sysUser.setUpdateBy(userName);
        sysUser.setUserId(loginUser.getUserId());
        sysUser.setPassword(encryptPassword);
        if (sysUserService.updateSysUser(sysUser) > 0) {
            // 更新缓存用户密码
            loginUser.setPassword(encryptPassword);
            tokenService.setLoginUser(loginUser);
            return ApiResponse.success();
        }
        throw new ServiceException("修改密码失败！");
    }

    /**
     * 头像上传
     */
    @Log(title = "用户头像", businessType = BusinessTypeEnum.UPDATE)
    @PostMapping("/avatar")
    public ApiResponse avatar(@RequestParam("avatar") MultipartFile file) {
        if (!file.isEmpty()) {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            String avatar = FileUploadUtils.upload(FileUploadUtils.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
            SysUser sysUser = new SysUser();
            sysUser.setUpdateBy(loginUser.getUsername());
            sysUser.setUserId(loginUser.getUserId());
            sysUser.setAvatar(avatar);
            if (sysUserService.updateSysUser(sysUser) > 0) {
                Map<String, Object> data = new HashMap<>(1);
                data.put("img", avatar);
                return success(data);
            }
        }
        throw new ServiceException("上传头像失败！");
    }
}
